package com.mljr.example.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ctakit.sdk.app.base.BaseFragment;
import com.ctakit.sdk.app.utils.DensityUtil;
import com.ctakit.sdk.app.utils.ViewUtil;
import com.ctakit.sdk.app.widget.list.smoothListView.SmoothListView;
import com.ctakit.sdk.app.widget.tab.home.HomeTabFragment;
import com.ctakit.sdk.exception.BusinessException;
import com.ctakit.sdk.util.ColorUtil;
import com.ctakit.sdk.view.annotation.LayoutContentId;
import com.ctakit.sdk.view.annotation.ViewInject;
import com.mljr.example.R;
import com.mljr.example.adapter.tab1.MerchantAdapter;
import com.mljr.example.base.MyBaseFragment;
import com.mljr.example.bean.tab1.ChannelIcon;
import com.mljr.example.bean.tab1.FilterData;
import com.mljr.example.bean.tab1.FilterEntity;
import com.mljr.example.bean.tab1.FilterTwoEntity;
import com.mljr.example.bean.tab1.HomeBanner;
import com.mljr.example.bean.tab1.Merchant;
import com.mljr.example.bean.tab1.Voucher;
import com.mljr.example.http.HttpManager;
import com.mljr.example.http.HttpServices;
import com.mljr.example.http.IHttpResult;
import com.mljr.example.ui.home.tab1.ChannelCustomViewPager;
import com.mljr.example.ui.home.tab1.FilterView;
import com.mljr.example.ui.home.tab1.HeaderAdViewView;
import com.mljr.example.ui.home.tab1.HeaderDividerViewView;
import com.mljr.example.ui.home.tab1.HeaderFilterViewView;
import com.mljr.example.ui.home.tab1.HeaderOperationViewView;
import com.mljr.example.ui.home.tab1.ModelUtil;
import com.mljr.example.util.AppUtils;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lizhenmin on 6/28/16.
 */
    @LayoutContentId(R.layout.activity_tab1)
    public class Tab1Fragment extends MyBaseFragment implements HomeTabFragment, SmoothListView.ISmoothListViewListener {
        @ViewInject(R.id.listView)
        SmoothListView smoothListView;
        @ViewInject(R.id.fv_top_filter)
        FilterView fvTopFilter;
        @ViewInject(R.id.rl_bar)
        RelativeLayout rlBar;
        @ViewInject(R.id.tv_title)
        TextView tvTitle;
        @ViewInject(R.id.view_title_bg)
        View viewTitleBg;


       private int mScreenHeight = 0;


        private List<HomeBanner> adList = new ArrayList<>(); // 广告数据
        private List<ChannelIcon> channelList = new ArrayList<>(); // 频道数据
        private List<Voucher> operationList = new ArrayList<>(); // 运营数据
        private List<Merchant> merchantList = new ArrayList<>(); // ListView数据

        private HeaderAdViewView listViewAdHeaderView; // 广告视图
        private ChannelCustomViewPager headerChannelViewPageView; // 频道视图
        private HeaderOperationViewView headerOperationViewView; // 运营视图
        private HeaderDividerViewView headerDividerViewView; // 分割线占位图
        private HeaderFilterViewView headerFilterViewView; // 分类筛选视图
        private FilterData filterData; // 筛选数据
        private MerchantAdapter mAdapter; // 主页数据

        private View itemHeaderAdView; // 从ListView获取的广告子View
        private View itemHeaderFilterView; // 从ListView获取的筛选子View
        private boolean isScrollIdle = true; // ListView是否在滑动
        private boolean isStickyTop = false; // 是否吸附在顶部
        private boolean isSmooth = false; // 没有吸附的前提下，是否在滑动
        private int titleViewHeight = 42; // 标题栏的高度
        private int filterPosition = -1; // 点击FilterView的位置：分类(0)、排序(1)、筛选(2)

        private int adViewHeight = 180; // 广告视图的高度
        private int adViewTopSpace; // 广告视图距离顶部的距离

        private int filterViewPosition = 4; // 筛选视图的位置
        private int filterViewTopSpace = 100; // 筛选视图距离顶部的距离

        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };




        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View  v = super.onCreateView(inflater, container, savedInstanceState);
            initLocation();
            initData();
            return v ;
        }


        private void initData() {

            mScreenHeight = ViewUtil.getScreenHeight();

            // 筛选数据
            filterData = new FilterData();
            filterData.setCategory(ModelUtil.getCategoryData());
            filterData.setSorts(ModelUtil.getSortData());
            filterData.setFilters(ModelUtil.getFilterData());

            new HttpManager(false, getFragment(), new IHttpResult() {

                @Override
                public void doRequest() throws BusinessException {
                    adList =   HttpServices.getHomeBannerList();
                    channelList =   HttpServices.getHomeIconList();
                    operationList = HttpServices.getVoucherList();
                    merchantList = HttpServices.getMerchantList(1,20);
                }

                @Override
                public void success() {
                    initTabView();
                    initListener();
                }

                @Override
                public boolean failed(BusinessException... ex) {
                    return false;
                }

            }).execute("");
            // 广告数据
            // adList = ModelUtil.getAdData();

            // 频道数据
            // channelList = ModelUtil.getChannelData();

            // 运营数据
            // operationList = ModelUtil.getOperationData();

            // ListView数据
            //travelingList = ModelUtil.getTravelingData();
        }

        public void initTabView() {
            fvTopFilter.setVisibility(View.GONE);

            // 设置筛选数据
            fvTopFilter.setFilterData(getActivity(), filterData);

            // 设置广告数据
            listViewAdHeaderView = new HeaderAdViewView(getActivity());
            listViewAdHeaderView.fillView(adList, smoothListView);

            // 设置频道数据
            headerChannelViewPageView = new ChannelCustomViewPager(getActivity());
            headerChannelViewPageView.fillView(channelList, smoothListView);

            // 设置运营数据
            headerOperationViewView = new HeaderOperationViewView(getActivity());
            headerOperationViewView.fillView(operationList, smoothListView);

            // 设置分割线
            // headerDividerViewView = new HeaderDividerViewView(getActivity());
            //  headerDividerViewView.fillView("", smoothListView);

            // 设置筛选数据
            headerFilterViewView = new HeaderFilterViewView(getActivity());
            headerFilterViewView.fillView(new Object(), smoothListView);

            // 设置ListView数据
            mAdapter = new MerchantAdapter(getActivity(), merchantList);
            smoothListView.setAdapter(mAdapter);

            filterViewPosition = smoothListView.getHeaderViewsCount() - 1;
        }

        @Override
        public String getPageName() {
            return "Tab1Fragment";
        }

        private void initListener() {


            // (假的ListView头部展示的)筛选视图点击
            headerFilterViewView.setOnFilterClickListener(new HeaderFilterViewView.OnFilterClickListener() {
                @Override
                public void onFilterClick(int position) {
                    filterPosition = position;
                    isSmooth = true;
                    smoothListView.smoothScrollToPositionFromTop(filterViewPosition, DensityUtil.dip2px(titleViewHeight));
                }
            });

            // (真正的)筛选视图点击
            fvTopFilter.setOnFilterClickListener(new FilterView.OnFilterClickListener() {
                @Override
                public void onFilterClick(int position) {
                    if (isStickyTop) {
                        filterPosition = position;
                        fvTopFilter.showFilterLayout(position);
                        if (titleViewHeight - 3 > filterViewTopSpace || filterViewTopSpace > titleViewHeight + 3) {
                            smoothListView.smoothScrollToPositionFromTop(filterViewPosition, DensityUtil.dip2px(titleViewHeight));
                        }
                    }
                }
            });

            // 分类Item点击
            fvTopFilter.setOnItemCategoryClickListener(new FilterView.OnItemCategoryClickListener() {
                @Override
                public void onItemCategoryClick(FilterTwoEntity entity) {
                    //fillAdapter(ModelUtil.getCategoryTravelingData(entity));
                }
            });

            // 排序Item点击
            fvTopFilter.setOnItemSortClickListener(new FilterView.OnItemSortClickListener() {
                @Override
                public void onItemSortClick(FilterEntity entity) {
                   // fillAdapter(ModelUtil.getSortTravelingData(entity));
                }
            });

            // 筛选Item点击
            fvTopFilter.setOnItemFilterClickListener(new FilterView.OnItemFilterClickListener() {
                @Override
                public void onItemFilterClick(FilterEntity entity) {
                   // fillAdapter(ModelUtil.getFilterTravelingData(entity));
                }
            });


            smoothListView.setRefreshEnable(true);
            smoothListView.setLoadMoreEnable(true);
            smoothListView.setSmoothListViewListener(this);
            smoothListView.setOnScrollListener(new SmoothListView.OnSmoothScrollListener() {
                @Override
                public void onSmoothScrolling(View view) {}

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    isScrollIdle = (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    if (isScrollIdle && adViewTopSpace < 0) return;

                    // 获取广告头部View、自身的高度、距离顶部的高度
                    if (itemHeaderAdView == null) {
                        itemHeaderAdView = smoothListView.getChildAt(1-firstVisibleItem);
                    }
                    if (itemHeaderAdView != null) {
                        adViewTopSpace = DensityUtil.px2dip(itemHeaderAdView.getTop());
                        adViewHeight = DensityUtil.px2dip(itemHeaderAdView.getHeight());
                    }

                    // 获取筛选View、距离顶部的高度
                    if (itemHeaderFilterView == null) {
                        itemHeaderFilterView = smoothListView.getChildAt(filterViewPosition - firstVisibleItem);
                    }
                    if (itemHeaderFilterView != null&&itemHeaderFilterView.getVisibility()==View.VISIBLE) {
                        filterViewTopSpace = DensityUtil.px2dip(itemHeaderFilterView.getTop());
                    }

                    // 处理筛选是否吸附在顶部
                    if (filterViewTopSpace > titleViewHeight) {
                        isStickyTop = false; // 没有吸附在顶部
                        fvTopFilter.setVisibility(View.GONE);
                    } else {
                        isStickyTop = true; // 吸附在顶部
                        fvTopFilter.setVisibility(View.VISIBLE);
                    }

                    Logger.d("firstVisibleItem:"+firstVisibleItem+"  "+filterViewPosition);
                    if (firstVisibleItem > filterViewPosition) {
                        isStickyTop = true;
                        fvTopFilter.setVisibility(View.VISIBLE);
                    }

                    if (isSmooth && isStickyTop) {
                        isSmooth = false;
                        fvTopFilter.showFilterLayout(filterPosition);
                    }

                    fvTopFilter.setStickyTop(isStickyTop);

                    // 处理标题栏颜色渐变
                    handleTitleBarColorEvaluate();
                }
            });
        }

        // 填充数据
        private void fillAdapter(List<Merchant> list) {
            if (list == null || list.get(0).isNoData()) {
                smoothListView.setLoadMoreEnable(false);
                int height = mScreenHeight - DensityUtil.dip2px(100); // 95 = 标题栏高度 ＋ FilterView的高度
                mAdapter.setData(ModelUtil.getNoDataEntity(height));
            } else {
                smoothListView.setLoadMoreEnable(list.size() > MerchantAdapter.ONE_REQUEST_COUNT);
                mAdapter.setData(list);
            }
        }

        // 处理标题栏颜色渐变
        private void handleTitleBarColorEvaluate() {
            float fraction;
            if (adViewTopSpace > 0) {
                fraction = 1f - adViewTopSpace * 1f / 60;
                if (fraction < 0f) fraction = 0f;
                rlBar.setAlpha(fraction);
                return ;
            }

            float space = Math.abs(adViewTopSpace) * 1f;
            fraction = space / (adViewHeight - titleViewHeight);
            if (fraction < 0f) fraction = 0f;
            if (fraction > 1f) fraction = 1f;
            rlBar.setAlpha(1f);
            viewTitleBg.setAlpha(1f);
            if (fraction >= 1f || isStickyTop) {
                isStickyTop = true;
                viewTitleBg.setAlpha(1f);
                rlBar.setBackgroundColor(AppUtils.getContext().getResources().getColor(R.color.theme_color));
            } else {
                // viewTitleBg.setAlpha(1f - fraction);
                rlBar.setBackgroundColor(ColorUtil.getNewColorByStartEndColor(AppUtils.getContext(), fraction, R.color.transparent, R.color.theme_color));
            }
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mLocationClient.onDestroy();
            if (listViewAdHeaderView != null) {
                listViewAdHeaderView.stopADRotate();
            }
        }

        @Override
        public BaseFragment getFragment() {
            return this;
        }


        public void onBackPressed() {
            if (!fvTopFilter.isShowing()) {

            } else {
                fvTopFilter.resetAllStatus();
            }
        }

        @Override
        public void onRefresh() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    smoothListView.stopRefresh();

                }
            }, 2000);
        }

        @Override
        public void onLoadMore() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    smoothListView.finishLoadMore();
                }
            }, 2000);
        }

    @Override
    public void onFragmentReVisible(Bundle bundle) {

    }

    @Override
    public void onSelectedAgain(Bundle bundle) {

    }
}

